/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.admin;

import app.Const;
import app.models.DaoKit;
import app.models.info.ShoppingMall;
import app.models.brand.BrandFormat;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-04-12 0:22
 * @since JDK 1.6
 */
public class FormatController extends BasicController {

    public static final String FORM_ATTR = "format";

    /**
     * The index route.
     */
    public void index() {
        render("index.ftl");
    }


    public void list() {
        final DatatablesCriterias criterias = getCriterias();
        Page<BrandFormat> floorPage = BrandFormat.dao.datatable(criterias);

        renderDataTables(floorPage, criterias);
    }


    public void create() {
        BrandFormat format = new BrandFormat();
        setAttr(FORM_ATTR, format);
        setAttr("mallblock", ShoppingMall.dao.malllist());
        setAttr("parentlist", BrandFormat.dao.listexcludeself(0));
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        render("item.ftl");
    }


    public void edit() {
        final int id = getParaToInt(0, 1);
        BrandFormat format = BrandFormat.dao.findById(id);

        setAttr(FORM_ATTR, format);
        setAttr("parentlist", BrandFormat.dao.listexcludeself(id));
        setAttr("mallblock", ShoppingMall.dao.malllist());
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        render("item.ftl");
    }


    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        if (DaoKit.batch_remove(SqlKit.sql("brandformat.remove"), ids)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }


    public void save() {
        BrandFormat format = getModel(BrandFormat.class);
        if (DaoKit.isNew(format)) {
            final Integer parent = format.getInt("parent");
            format.set("rank", (parent != null && parent > 0) ? BrandFormat.dao.findById(parent).getInt("rank") + 1 : 1);
            format.save();
        } else {
            format.update();
        }
        redirect("/admin/format");
    }
}